package com.zwb.service.controller;

import com.zwb.service.dto.AdminLoginParamDto;
import com.zwb.service.pojo.Admin;
import com.zwb.service.service.IAdminService;
import com.zwb.service.common.JwtTokenUtil;
import com.zwb.service.vo.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.ui.ModelMap;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 头发又黑又长
 * @Date 2022/8/26 20:56
 * @email zwb15083976291@163.com
 */
@Api(tags = "登录管理")
@RestController
public class LoginController {

    @Autowired
    private IAdminService adminService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public R login(@RequestBody AdminLoginParamDto adminLoginParam, HttpServletRequest request) {
        String code = adminLoginParam.getCode();
        Object captcha = request.getSession().getAttribute("captcha");
        if (ObjectUtils.isEmpty(captcha) || ObjectUtils.isEmpty(code)) {
            return R.error("验证码为空");
        }

        if (!((String) captcha).equals(code)) {
            return R.error("验证码错误");
        }
        Admin loginAdmin;
        try {
            loginAdmin = (Admin) adminService.loadUserByUsername(adminLoginParam.getUserName());
        } catch (UsernameNotFoundException e) {
            return R.error("用户名或密码错误");
        }
        if (!this.passwordEncoder.matches(adminLoginParam.getPassword(), loginAdmin.getPassword())) {
            return R.error("用户名或密码错误");
        }
        if (!loginAdmin.isEnabled()) {
            return R.error("账号已被禁用，请联系管理员");
        }

        // 添加到 security 的全文上下文中
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                loginAdmin, null, loginAdmin.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        String token = jwtTokenUtil.generatorToken(loginAdmin);
        ModelMap data = new ModelMap("token", token);
        data.addAttribute("header", this.tokenHead);
        return R.success("登录成功", data);

    }

    @ApiOperation("退出登录")
    @PostMapping("/logout")
    public R logout() {
        return R.success("退出登录成功");
    }

    @ApiOperation("获取当前登录用户信息")
    @GetMapping("/admin/info")
    public R info() {
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        Admin logAdmin = adminService.getAdminByUsername(name);
        logAdmin.setPassword(null);
        return R.success(logAdmin);
    }

}
